package design2;

import java.util.ArrayList;
import java.util.Random;

/**
 * 习题类 - 设计二版本，继承ArrayList
 */
public class Exercise extends ArrayList<BinaryOperation> {
    private Random random;
    
    /**
     * 默认构造方法
     */
    public Exercise() {
        super();
        this.random = new Random();
    }
    
    /**
     * 检查习题集中是否已包含某个算式
     */
    public boolean contains(BinaryOperation op) {
        for (BinaryOperation operation : this) {
            if (operation.equals(op)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 生成指定数量的加法习题
     */
    public void generateAdditionExercise(int operationCount) {
        this.clear();
        while (this.size() < operationCount) {
            AdditionOperation op = new AdditionOperation();
            
            if (!contains(op)) {
                this.add(op);
            }
        }
    }
    
    /**
     * 生成指定数量的减法习题
     */
    public void generateSubstractExercise(int operationCount) {
        this.clear();
        while (this.size() < operationCount) {
            SubstractOperation op = new SubstractOperation();
            
            if (!contains(op)) {
                this.add(op);
            }
        }
    }
    
    /**
     * 生成指定数量的混合习题
     */
    public void generateBinaryExercise(int operationCount) {
        this.clear();
        while (this.size() < operationCount) {
            BinaryOperation op;
            if (random.nextBoolean()) {
                op = new AdditionOperation();
            } else {
                op = new SubstractOperation();
            }
            
            if (!contains(op)) {
                this.add(op);
            }
        }
    }
    
    /**
     * 格式化显示所有习题
     */
    public void formateAndDisplay(int columnsPerRow) {
        if (this.isEmpty()) {
            System.out.println("习题集为空！");
            return;
        }
        
        for (int i = 0; i < this.size(); i++) {
            BinaryOperation op = this.get(i);
            System.out.printf("%2d. %-10s", i + 1, op.toString());
            
            // 换行控制
            if ((i + 1) % columnsPerRow == 0) {
                System.out.println();
            }
        }
        
        // 如果最后一行不满，也要换行
        if (this.size() % columnsPerRow != 0) {
            System.out.println();
        }
        System.out.println();
    }
}